package org.example.todolist.service.impl;

import org.example.todolist.entity.TodoList;
import org.example.todolist.mapper.ListMapper;
import org.example.todolist.mapper.TaskMapper;
import org.example.todolist.service.ListService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;

/**
 * 列表服务实现类
 */
@Service
public class ListServiceImpl implements ListService {

    @Autowired
    private ListMapper listMapper;

    @Autowired
    private TaskMapper taskMapper;

    @Override
    public TodoList createList(TodoList list) {
        // 设置创建时间
        list.setCreatedAt(LocalDateTime.now());
        // 插入列表
        int resultCount = listMapper.insert(list);
        if (resultCount == 0) {
            return null;
        }
        return list;
    }

    @Override
    public TodoList getListById(Integer id) {
        return listMapper.selectById(id);
    }

    @Override
    public ArrayList<TodoList> getListsByUserId(Integer userId) {
        return listMapper.selectByUserId(userId);
    }

    @Override
    public boolean updateList(TodoList list) {
        int resultCount = listMapper.update(list);
        return resultCount > 0;
    }

    @Override
    @Transactional
    public boolean deleteList(Integer id) {
        // 删除列表下的所有任务
        taskMapper.deleteByListId(id);
        // 删除列表
        int resultCount = listMapper.deleteById(id);
        return resultCount > 0;
    }

    @Override
    public boolean checkBelonging(Integer id, Integer userId) {
        int resultCount = listMapper.checkBelonging(id, userId);
        return resultCount > 0;
    }
}
